<template>
  <div>
    <div v-if="groupList && groupList.length">
      <div v-for="(item, index) in groupList" :key="index">
        <div class="bgc-white p24 mt12 br8 flex-center" style="height: 100px">
          <a-tooltip :title="item.name">
            <div class="flex-center flex-shrink-0 border-right" style="width: 200px">
              <div class="noShowIcon" style="cursor: pointer">
                <a-icon type="file-text" theme="filled" />
              </div>
              <div class="fw500 fs18 ellipsis pr20 flex-1 tc-l1">{{ item.name }}</div>
            </div>
          </a-tooltip>
          <div class="flex-center-between ml24 flex-1">
            <div>
              <div class="ta-center fs12 tc-l2">月份</div>
              <div class="ta-center fs14 tc-l3 mt8">{{ formatYM(item.yearly, item.monthly) }}</div>
            </div>
            <div>
              <div class="ta-center fs12 tc-l2">创建人</div>
              <div class="ta-center fs14 tc-l3 mt8">{{ item.createUserName }}</div>
            </div>
            <div>
              <div class="ta-center fs12 tc-l2">创建时间</div>
              <div class="ta-center fs14 tc-l3 mt8">{{ $dayjs(item.gmtCreate).format("YYYY-MM-DD") }}</div>
            </div>
            <a-space>
              <span class="pointer tc-theme" @click="goDetail(item)">详情</span>
              <span class="pointer tc-theme" @click="showEdit(item)">编辑</span>
              <a-popconfirm :title="'确定删除?'" @confirm="deleteItem(item.subjectId)">
                <span v-if="!item.hrMonthlySalarySummaryVOList || item.hrMonthlySalarySummaryVOList.length === 0" class="pointer tc-theme">
                  删除
                </span>
              </a-popconfirm>
            </a-space>
          </div>
        </div>
      </div>
      <div class="flex-center-end mt24">
        <a-pagination
          v-model="pagination.current"
          :total="pagination.total"
          :pageSize.sync="pagination.pageSize"
          :showQuickJumper="pagination.showQuickJumper"
          :showSizeChanger="pagination.showSizeChanger"
          :showTotal="pagination.showTotal"
          :size="pagination.size"
          :pageSizeOptions="pagination.pageSizeOptions"
          @change="onShowSizeChange"
          @showSizeChange="onShowSizeChange"
        />
      </div>
    </div>
    <div v-else style="padding: 120px 0px 560px 0px; background-color: #f2f3f5">
      <a-empty />
    </div>
    <a-modal v-model="addVisible" :title="modalTitle" @ok="save" @cancel="onCancel">
      <a-form-model ref="ruleForm" :model="addForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }" style="margin-top: 15px">
        <a-form-model-item ref="name" prop="name" :rules="{ required: true, message: '请输入' }" label="分组名称">
          <a-input placeholder="请输入名称" v-model="addForm.name" style="width: 240px" />
        </a-form-model-item>
        <a-form-model-item ref="date" prop="date" :rules="{ required: true, message: '请选择' }" label="明细表月份">
          <a-month-picker placeholder="请选择月份" v-model="addForm.date" style="width: 240px" />
        </a-form-model-item>
        <a-form-model-item ref="companyInfoList" prop="companyInfoList" :rules="{ required: true, message: '请选择' }" label="选择用工单位">
          <a-tree-select
            v-model="addForm.companyInfoList"
            :tree-data="companyDataList"
            :filterTreeNode="false"
            :replaceFields="replaceFields2"
            labelInValue
            treeCheckable
            placeholder="请选择"
            style="width: 240px"
            @search="treeSearch"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { findCompanyGroup } from "@/api/company/contract";
export default {
  name: "",
  components: {},
  mixins: [],
  props: {
    date: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      tempItem: null,
      modalTitle: "",
      replaceFields2: {
        children: "companyList",
        title: "name",
        key: "uuid",
        value: "uuid"
      },
      addVisible: false,
      addForm: {},
      groupList: [],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      companyDataList: [],
      flatDataList: []
    };
  },
  computed: {},
  watch: {
    date: {
      handler(newVal) {
        if (newVal) {
          this.loadData();
        }
      },
      immediate: true
    }
  },
  created() {},
  mounted() {
    this.findCompanyGroup();
  },
  methods: {
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.companyDataList = this.addTreeSlot(res.data);
          this.flatten(this.companyDataList);
          this.addForm.companyInfoList = this.addForm.companyInfoList
            ? JSON.parse(JSON.stringify(this.addForm.companyInfoList))
            : undefined;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    addTreeSlot(data) {
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        el.scopedSlots = { title: "custom" };
        this.addTreeSlot(el.companyList);
      });
      return data;
    },
    flatten(list) {
      if (list !== null) {
        list.forEach((item) => {
          this.flatDataList.push(item);
          this.flatten(item.companyList);
        });
      }
    },
    onShowSizeChange(current, pageSize) {
      this.pagination.current = current;
      this.pagination.pageSize = pageSize;
      this.loadData();
    },
    formatYM(yl, ml) {
      if (yl) {
        return `${yl}-${ml < 10 ? "0" : ""}${ml}`;
      }
      return "--";
    },
    onCancel() {
      this.addVisible = false;
    },
    goDetail(item) {
      localStorage.setItem("kehumingxibiao_item", JSON.stringify(item));
      this.$router.push({
        path: "kehumingxibiao/customerDetail",
        query: {
          monthly: this.$dayjs(this.date).format("MM"),
          yearly: this.$dayjs(this.date).format("YYYY"),
          formType: item.customerDetailsType,
          groupType: item.subjectType
        }
      });
    },
    showEdit(item) {
      console.log(item.companyIds);
      this.tempItem = item;
      this.modalTitle = "编辑自定义分组";
      this.addVisible = true;
      this.addForm = {
        date: this.$moment(`${item.yearly}-${item.monthly < 10 ? "0" : ""}${item.monthly}`, "YYYY-MM"),
        name: item.name,
        companyInfoList: this.flatDataList.filter((li) => item.companyIds.includes(li.id)).map((li) => ({ value: li.uuid, label: li.name }))
      };
    },
    showAdd() {
      this.modalTitle = "新增自定义分组";
      this.addVisible = true;
      this.addForm = {};
    },
    loadData() {
      this.$request({
        url: `/hr/api/v1/customerDetailsNew/selectCustomGroupingBySiteAndMonthly`,
        params: {
          monthly: this.$dayjs(this.date).format("MM"),
          yearly: this.$dayjs(this.date).format("YYYY"),
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize,
          customerDetailsType: "customer"
        }
      })
        .then((res) => {
          this.groupList = res.data.entities;
          this.pagination.total = res.data.entityCount;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    save() {
      const companyArr = [];
      this.addForm.companyInfoList.forEach((item) => {
        this.flatDataList.forEach((item2) => {
          if (item2.uuid && item2.uuid === item.value) {
            companyArr.push(item2.id);
          }
        });
      });
      if (this.modalTitle === "编辑自定义分组") {
        this.$request({
          url: `/hr/api/v1/companyCustomGroupings`,
          method: "put",
          data: {
            id: this.tempItem.subjectId,
            name: this.addForm.name,
            moduleCode: "customerDetails",
            monthly: this.$dayjs(this.addForm.date).format("MM"),
            yearly: this.$dayjs(this.addForm.date).format("YYYY"),
            companyIds: companyArr.join(",")
          }
        })
          .then((res) => {
            this.$message.success("编辑成功");
            this.loadData();
            this.onCancel();
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$request({
          url: `/hr/api/v1/companyCustomGroupings`,
          method: "post",
          data: {
            name: this.addForm.name,
            moduleCode: "customerDetails",
            monthly: this.$dayjs(this.addForm.date).format("MM"),
            yearly: this.$dayjs(this.addForm.date).format("YYYY"),
            companyIds: companyArr.join(",")
          }
        })
          .then((res) => {
            this.$message.success("新增成功");
            this.loadData();
            this.onCancel();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    deleteItem(companyCustomGroupingId) {
      this.$request({
        url: `/hr/api/v1/companyCustomGroupings/${companyCustomGroupingId}`,
        method: "delete"
      })
        .then((res) => {
          this.$message.success("删除成功");
          this.loadData();
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .ant-select-selection--multiple {
  max-height: 400px;
  overflow-y: auto;
}

.noShowIcon {
  width: 32px;
  height: 32px;
  background: var(--primary);
  border-radius: 8px;
  margin-right: 12px;
  color: #ffffff;
  line-height: 32px;
  text-align: center;
  box-shadow: 0px 2px 8px 1px var(--primary);
  flex-shrink: 0;
}
</style>
